<?php
/**
 * [woniu] Copyright (c) 2016/8/18
 * join.ctrl
 * 报名入口控制器
 */

defined('IN_IA') or exit('Access Denied');
if (empty($_W['fans']['nickname'])) {
    $_W['fans'] = getInfo();
}
$op = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
$pagetitle = '报名信息填写';
$activityid = intval($_GPC['activityid']);
$activity = model_activity::getSingleActivity($activityid, '*');
$proid = intval($_GPC['proid']);
$teamnum = intval($_GPC['teamnum']) ? intval($_GPC['teamnum']) : 1;
$form = unserialize($activity['form']);//系统表单
$activity['prize'] = unserialize($activity['prize']);//积分
if ($_SESSION['status'] != 'login') {
    include $this->template('aitimt/login');
    exit;
}
if ($_W['container'] != 'wechat') {
    aide_message('请用微信打开此链接接报名', '', 'error', '点确定返回');
}
if ($activity['is_show'] == 0 || $activity['review'] != 1) {
    aide_message('当前活动没有开放报名', '', 'error', '点确定返回');
}
if ($_W['_config']['guanzhu_join'] == 2 && empty($_W['fans']['follow'])) {
    aide_message('您还未关注,不能报名', app_url('activity/detail/display', array('activityid' => $activityid)), 'warning');
}

$blacklist = pdo_get('aide_member_blacklist', array('uid' => $_W['member']['uid']), array('uid'));
if ($blacklist['uid']) {
    aide_message('对不起您被主办方屏蔽了', app_url('activity/detail/display', array('activityid' => $activityid)), 'error',
        '请联系主办方解封');
}
if ($activity['costcredit'] && $activity['costcredit'] > $_W['member']['credit1']) {
    aide_message('对不起您的积分不足', '', 'error', '参与当前活动需要 ' . $activity['costcredit'] . ' 积分，分享当前活动可以赚取积分哦！');
}
//验证名额，每次进入加载剩余名额数量、及规格
$condition = " activityid = $activityid and status <> 5 and (status <> 0 or paytype = 'delivery')";
$quota = $activity['quota'];

$prodata = pdo_fetchall("SELECT * FROM " . tablename('aide_activity_pro') . " WHERE id=$proid  ORDER BY  id ASC");
$activity['aprice'] = $prodata[0]['pprice'];
$quota = $prodata[0]['ptotal'];
$price = $activity['aprice'];
$pay_price = $activity['aprice'];
if($prodata[0]['total']>1){
    for ($i=0;$i<$prodata[0]['total'];$i++){
        $totalArr[]=$i;
    }
}

$condition = "uniacid={$_W['uniacid']} and activityid = $activityid and entrystatus=1";
$condition .= $proid ? " and pid = $proid" : '';
$joinnum = pdo_fetchcolumn("SELECT SUM(teamnum) FROM " . tablename('aide_activity_records') . " WHERE $condition");
$joinnum = $joinnum ? $joinnum : 0;

if ($_W['plugin']['card']['config']['card_enable'] && $yearcard['buy']) {//年卡
    if ($activity['atype'] == 2) {
        if (!$activity['prize']['cardper']['enable']) {//年卡价格
            //$price = $activity['marketprice'];
            $vipdeduct = $activity['aprice'] - $activity['marketprice'];
            $pay_price = $activity['marketprice'];
        } else {//年卡打折
            $yc['percent'] = $activity['prize']['cardper']['percent'];
        }
    }
    if ($_W['plugin']['card']['config']['credit_double']) {
        $credit_double = 1;
    }
}

$dc = $_GPC['dc'] == 'yes' ? true : false; //是否积分抵扣
$pay_price = sprintf("%.2f", $pay_price * $teamnum);
$afterMarketing = model_records::getafterMarketing($pay_price, $teamnum, $activityid, $dc, $yc); //获取优惠后的价格等参数
$pay_price = $afterMarketing['pay_price'];  //营销后的价格
$vipdeduct = empty($vipdeduct) ? $afterMarketing['cardReduce'] : $vipdeduct; //高级vip优惠费用

if ($_W['isajax'] && $op == 'getprice') {
    $params = array(
        'price' => $price,
        'pay_price' => $pay_price,
        'joinnum' => $joinnum,
        'm1' => $afterMarketing['m1'],
        'm2' => $afterMarketing['m2'],
        'm3' => $afterMarketing['m3'],
        'm4' => $afterMarketing['m4'],
        'max' => $afterMarketing['max'],
        'p' => $afterMarketing['p'],
        'deductMoney' => $afterMarketing['deductMoney'],
        'deductCredit' => $afterMarketing['deductCredit'],
        'orderMarket' => $afterMarketing['orderMarket'],
        'cardReduce' => $afterMarketing['cardReduce'],
        'token' => $_W['token']
    );

    die(json_encode(array('errno' => 0, 'params' => $params)));
}

if ($op == 'display') {
    load()->model('mc');
    $marketing = model_activity::getMarketing($activityid);//优惠
    $openid = $_W['fans']['openid'];
    $commendList = pdo_fetchall("SELECT id,remarks FROM " . tablename('aide_form_data_common') . " WHERE openid='$openid' AND status>0 AND uniacid='{$_W['uniacid']}' ORDER BY  id DESC");
    $cid = (int)$_GPC['cid'];
    $recordid=(int)$_GPC['recordid'];
    if (!empty($recordid)) {
        $totalArr = pdo_fetchall("SELECT * FROM " . tablename('aide_form_data_common') . " WHERE rid=$recordid  ORDER BY id ASC");
        $rtemp = pdo_fetch("SELECT reward FROM " . tablename('aide_activity_records') . " WHERE id = $recordid LIMIT 1");
        $rewardid=$rtemp['reward'];
        $reward = pdo_fetch("SELECT * FROM " . tablename('aide_activity_reward') . " WHERE id=$rewardid LIMIT 1");
    }
    $activityForm = model_activity::getNumActivityForm($activityid, 'app');//读取表单
    $condition = "pid = $proid and openid='{$_W['openid']}'";
    $findUser = pdo_fetch("SELECT id FROM " . tablename('aide_activity_records') . " WHERE $condition");
if ($findUser['id']==$recordid){
    $findUser='';
}
    if ($joinnum >= $quota && $quota > 0) {
        aide_message('很遗憾！名额已经满了', app_url('home/index/detail', array('activityid' => $activityid)), 'warning');
    }
    $is_back = $_GPC['is_back'];
    if($_W['uniacid']==2){
        include $this->template('aitimt/join2');
        exit;
    }
    include $this->template('aitimt/join');
    exit;
}
if ($_W['isajax'] && $op == 'join') {
    $recordid=(int)$_GPC['recordid'];
    if (!empty($recordid)) {
        $rtemp = pdo_fetch("SELECT reward FROM " . tablename('aide_activity_records') . " WHERE id = $recordid LIMIT 1");
        $rewardid=$rtemp['reward'];
        $reward = pdo_fetch("SELECT * FROM " . tablename('aide_activity_reward') . " WHERE id=$rewardid LIMIT 1");
    }
    $data_member = $_GPC['member'];
    $data = array(
        'uid' => (int)$_W['member']['uid'],
        'activityid' => $activityid,
        'uniacid' => (int)$_W['uniacid'],
        'openid' => (string)$_W['openid'],
        'teamnum' => $teamnum,
        'reward' =>  $_GPC["form_item_val_0"],//打赏金额
        'nickname' => (string)$_W['member']['nickname'],
        'headimgurl' => (string)$_W['member']['avatar'],
        'orderno' => createUniontid(),
        'realname' => (string)$data_member['realname'],
        'mobile' => (string)$data_member['mobile'],
        'gender' => (int)$_GPC['gender'] == 0 ? '保密' : ($_GPC['gender'] == 1 ? '男' : '女'),
        'pic' => (string)$data_member['pic'],
        'msg' => htmlspecialchars_decode($_GPC['msg']),
        'pid' => $proid ? $proid : 0,
        'review' => (int)$activity['hasreview'] ? 0 : 1,
        'status' => 2,
        'merchantid' => $activity['merchantid'] ? $activity['merchantid'] : 0,
    );
    $condition = "pid = $proid and status > 0 and openid='{$_W['openid']}'";
    $findUser = pdo_fetch("SELECT id FROM " . tablename('aide_activity_records') . " WHERE $condition");
    if ($findUser['id']==$recordid){
        $findUser='';
    }
    if (!empty($findUser) && !$activity['hasjoin']) {
        if ($_W['isajax']) {
            die(json_encode(array('errno' => 1, 'errmsg' => '你已经报名成功')));
            exit;
        } else {
            die(json_encode(array('errno' => 1, 'errmsg' => '不能重复报名')));
            exit;
        }
    } else {
        if ($quota > 0) {
            $joinnum = model_records::getJoinNum($activityid, $proid) + $activity['falsenum'];
            if ($joinnum >= $quota) {
                die(json_encode(array('errno' => 1, 'errmsg' => '很遗憾！名额已经满了')));
                exit;
            } elseif ($joinnum + $teamnum > $quota) {
                die(json_encode(array('errno' => 1, 'errmsg' => "活动仅剩 " . ($quota - $joinnum) . " 个名额")));
                exit;
            }
        }
    }
    if (!empty($recordid)){
        $prodata = pdo_fetchall("SELECT * FROM " . tablename('aide_activity_pro') . " WHERE id=$proid  ORDER BY  id ASC");
        $proTotal=$prodata[0]['total'];
        $rewardData=[
            'nickname'=>$data['nickname'],
            'reward'=>$data['reward'],
            'createtime'=>time(),
        ];
        $rewordid=$reward['id'];
        pdo_update('aide_activity_reward', $rewardData, ['id' => $rewordid]);
        if($proTotal>1){
            $data['realname']=$_GPC['member1']['realname'];
            $data['mobile']=$_GPC['member1']['mobile'];
            $data['teamnum']=$proTotal;
            $data['leader']=$data['uid'];
            $data['reward']=$rewordid;
            pdo_update('aide_activity_records', $data, ['id' => $recordid]);
            for ($i=0;$i<$proTotal;$i++){
                $time='member'. $i;
                $pro=$_GPC[$time];
                if ($proTotal==3&&$i>0){
                    if (!empty($pro['realname'])){
                        $pro['realname']  = $pro['realname'].'(随行)';
                    }
                }
                $pro['grade']=$data_member['grade']?$data_member['grade']:0;
                $pro['leader']=$data['uid'];
                setPro($pro,$recordid);
            }
        } else{
            $data['realname']=$_GPC['member1']['realname'];
            $data['mobile']=$_GPC['member1']['mobile'];
            $data['reward']=$rewordid;
            $pro['leader']=$data['uid'];
            $data['leader']=$data['uid'];
            pdo_update('aide_activity_records', $data, ['id' => $recordid]);
            $pro=$_GPC['member0'];
            setPro($pro,$recordid);
        }
    } else {
        $prodata = pdo_fetchall("SELECT * FROM " . tablename('aide_activity_pro') . " WHERE id=$proid  ORDER BY  id ASC");
        $proTotal=$prodata[0]['total'];
        $rewardData=[
            'nickname'=>$data['nickname'],
            'reward'=>$data['reward'],
            'createtime'=>time(),
        ];
        $result = pdo_insert('aide_activity_reward', $rewardData);
        $rewordid=pdo_insertid();
        if($proTotal>1){
            $data['realname']=$_GPC['member1']['realname'];
            $data['mobile']=$_GPC['member1']['mobile'];
            $data['teamnum']=$proTotal;
            $data['leader']=$data['uid'];
            $data['reward']=$rewordid;
            $result = pdo_insert('aide_activity_records', $data);
            $recordid = pdo_insertid();
            for ($i=0;$i<$proTotal;$i++){
                $time='member'. $i;
                $pro=$_GPC[$time];
                if ($proTotal==3&&$i>0){
                    if (!empty($pro['realname'])){
                        $pro['realname']  = $pro['realname'].'(随行)';
                    }
                }
                $pro['grade']=$data_member['grade']?$data_member['grade']:0;
                $pro['leader']=$data['uid'];
                setPro($pro,$recordid);
            }
        } else{
            $data['realname']=$_GPC['member1']['realname'];
            $data['mobile']=$_GPC['member1']['mobile'];
            $data['reward']=$rewordid;
            $pro['leader']=$data['uid'];
            $data['leader']=$data['uid'];
            $result = pdo_insert('aide_activity_records', $data);
            $recordid = pdo_insertid();
            $pro=$_GPC['member0'];
            setPro($pro,$recordid);
        }
    }
    if ($rewardData['reward']>0){
        die(json_encode(array('errno' => 0, 'recordid' => $recordid,'is_pay'=>1)));

    }else{
        die(json_encode(array('errno' => 0, 'recordid' => $recordid,'is_pay'=>0)));

    }

}
//项目内容填充
function setPro($arr,$rid){
    global $_W;
    $pro = array(
        'uniacid'=> $_W['uniacid'],
        'rid'=> $rid,
        'leader'=> (int)$arr['leader'],
        "mobile"  => $arr['mobile']?(string)$arr['mobile']:0,
        "realname"  => $arr['realname']?(string)$arr['realname']:0,
        "studentid" =>$arr['studentid']?(string)$arr['studentid']:0,
        "grade"  =>$arr['grade']?(string)$arr['grade']:0,
        "idcard"  =>$arr['idcard']?(string)$arr['idcard']:0,
        "sex"  =>$arr['sex']?(string)$arr['sex']:0,
    );
    if ($arr['id']!=null){
        $pro['id']=$arr['id'];
        pdo_update ('aide_form_data_common', $pro, array ('id' => $pro['id']));
    }elseif($arr['realname']!=null){
        pdo_insert ('aide_form_data_common', $pro);
    }
}
if ($_W['isajax'] && $op == 'validquota') {//验证名额填写时的剩余名额；
    if ($quota > 0) {
        if ($joinnum >= $quota) {
            die(json_encode(array('errno' => 1, 'message' => "很遗憾！名额已经满了")));
        } elseif ($joinnum + $teamnum > $quota) {
            die(json_encode(array('errno' => 1, 'message' => "当前活动仅剩 " . ($quota - $joinnum) . ' 个名额')));
        }
    }
    die(json_encode(array('errno' => 0)));
}

//人脸上传
if ($op == 'faceimgupload') {
    if ($activity['has_record_image'] == 1) {
        $file = $_FILES['jianlu'];
        $file_name = str_pad(date('dHis', time()), 8, '9', STR_PAD_LEFT) . str_pad(rand(0, 99), 2, '0', STR_PAD_LEFT);
        $upload = file_upload2($_W['uniacid'], $file, $file_name);
        if (is_error($upload)) {
            $out = array(
                'errno' => 1,
                'errmsg' => $upload['message']
            );
            echo json_encode($out);
            exit;
        } else {
            $insert_data = array(
                'uniacid' => $_W['uniacid'],
                'activityid' => $activity['id'],
                'openid' => $_W['openid'],
                'file_name' => $file_name,
                'file_path' => '/addons/aide_activity' . $upload['path']
            );
            $res = pdo_insert("aide_faceimg", $insert_data);
            if ($res) {
                $faceimg_id = pdo_insertid();
                //百度人脸识别
                $model_baidu = new model_baidu();
                $file_path = IA_ROOT . '/addons/aide_activity' . $upload['path'];
                $faceRes = $model_baidu->checkPictureToCheckFace($file_path);
                //人脸不通过，返回错误，并删掉数据和图片
                if ($faceRes['result'] != true) {
                    pdo_delete('aide_faceimg', array('id' => $faceimg_id));
                    unlink($file_path);
                    $out = array(
                        'errno' => 1,
                        'errmsg' => $faceRes['err_msg']
                    );
                    echo json_encode($out);
                    exit;
                }
                //上传成功，删除旧数据
                if ($_GPC['faceimg_id'] > 0) {
                    $condition = array(
                        'id' => $_GPC['faceimg_id'],
                        'uniacid' => $_W['uniacid'],
                        'activityid' => $activity['id'],
                        'openid' => $_W['openid']
                    );
                    $old = pdo_get('aide_faceimg', $condition);
                    if ($old) {
                        pdo_delete('aide_faceimg', array('id' => $old['id']));
                        $file = IA_ROOT . $old['file_path'];
                        unlink($file);
                    }
                }
            } else {
                $out = array(
                    'errno' => 1,
                    'errmsg' => '上传保存失败'
                );
                echo json_encode($out);
                exit;
            }
            $data = array(
                'faceimg_id' => $faceimg_id,
                'file_name' => $file_name,
                'file_path' => '/addons/aide_activity' . $upload['path']
            );
            $out = array(
                'errno' => 0,
                'errmsg' => 'ok',
                'data' => $data
            );
            echo json_encode($out);
            exit;
        }
    }
}

function file_upload2($uniacid, $file, $attname = '', $name = '')
{
    load()->func('file');
    if (empty($file)) {
        return error(-1, '没有上传内容');
    }
    $deftype = array('png', 'jpg');
    $extention = pathinfo($file['name'], PATHINFO_EXTENSION);
    if (!in_array(strtolower($extention), $deftype)) {
        return error(-1, '不允许上传此类文件');
    }
    $result = array();

    if (empty($name) || $name == 'auto') {
        $result['path'] = "/uploadfile/" . $uniacid . "/" . date('Ym') . '/';
        mkdirs(MODULE_ROOT . $result['path']);
        do {
            if (empty($attname)) {
                $nowname = random(20);
                $filename = $nowname . ".{$extention}";
            } else {
//                $file['name'] = str_replace(".".$extention,'',$file['name']);
//                $filename = $file['name'] .random(2). ".{$extention}";
                $nowname = $attname;
//                $filename = $attname . ".{$extention}";
                $filename = $attname . ".jpg";
            }
        } while (file_exists(MODULE_ROOT . $result['path'] . $filename));
        $result['path'] .= $filename;
    } else {
        $result['path'] = $name . '.' . $extention;
    }

    if (!file_move($file['tmp_name'], MODULE_ROOT . '/' . $result['path'])) {
        return error(-1, '保存上传文件失败');
    }
    $result['nowname'] = $nowname;
    $result['success'] = true;
    return $result;
}

function updateOrInsert($table, $data, $where = '')
{
    if (empty($where)) {
        pdo_insert($table, $data);
        return pdo_insertid();
    } else {
        $result = pdo_update($table, $data, $where);
        if (!empty($result)) {
            return $where;
        } else {
            pdo_insert($table, $data);
            return pdo_insertid();
        }
    }
}
